from PySide6.QtWidgets import QApplication
import sys
from views.main_window import MainWindow
from PySide6.QtGui import QIcon
from viewmodels.main_vm import MainViewModel
import darkdetect
import json
from utils.path_processor import resource_path


def load_theme():
    try:
        config_path = resource_path("config/config.json")
        with open(config_path, "r") as f:
            config = json.load(f)
            return config.get("theme", "system")
    except FileNotFoundError:
        return "system"

def apply_theme(app, theme):
    theme_map = {
        "dark": "dark",
        "light": "light",
        "system": "dark" if darkdetect.isDark() else "light"
    }
    qss_file = resource_path(f"resources/styles/{theme_map.get(theme, 'light')}.qss")
    try:
        with open(qss_file, "r") as f:
            app.setStyleSheet(f.read())
    except FileNotFoundError:
        pass


if __name__ == "__main__":
    app = QApplication(sys.argv)
    app.setWindowIcon(QIcon(resource_path("resources/image/Cartethyia_icon.ico")))

    theme = load_theme()
    apply_theme(app, theme)

    view_model = MainViewModel()
    window = MainWindow(view_model)
    window.show()
    view_model.refresh_instances()

    sys.exit(app.exec())
